package com.uduemc.biso.node.module.common.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.uduemc.biso.node.core.common.dto.download.FeignRepertoryImport;
import com.uduemc.biso.node.core.common.sysconfig.DownloadSysConfig;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.core.entities.SCategoriesQuote;
import com.uduemc.biso.node.core.entities.SDownload;
import com.uduemc.biso.node.core.entities.SDownloadAttr;
import com.uduemc.biso.node.core.entities.SDownloadAttrContent;
import com.uduemc.biso.node.core.entities.SRepertoryQuote;
import com.uduemc.biso.node.core.entities.SSystem;
import com.uduemc.biso.node.core.entities.custom.CategoryQuote;
import com.uduemc.biso.node.core.entities.custom.Download;
import com.uduemc.biso.node.core.entities.custom.DownloadAttrAndContent;
import com.uduemc.biso.node.core.entities.custom.RepertoryQuote;
import com.uduemc.biso.node.core.utils.SystemConfigUtil;
import com.uduemc.biso.node.module.common.mapper.CCategoriesMapper;
import com.uduemc.biso.node.module.common.mapper.CDownloadAttrContentMapper;
import com.uduemc.biso.node.module.common.mapper.CDownloadMapper;
import com.uduemc.biso.node.module.common.mapper.CRepertoryMapper;
import com.uduemc.biso.node.module.common.service.CDownloadService;
import com.uduemc.biso.node.module.service.HRepertoryService;
import com.uduemc.biso.node.module.service.SCategoriesQuoteService;
import com.uduemc.biso.node.module.service.SCategoriesService;
import com.uduemc.biso.node.module.service.SDownloadAttrContentService;
import com.uduemc.biso.node.module.service.SDownloadAttrService;
import com.uduemc.biso.node.module.service.SDownloadService;
import com.uduemc.biso.node.module.service.SRepertoryQuoteService;
import com.uduemc.biso.node.module.service.SSystemService;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;

@Service
public class CDownloadServiceImpl implements CDownloadService {

	@Autowired
	private SSystemService sSystemServiceImpl;

	@Autowired
	private SDownloadService sDownloadServiceImpl;

	@Autowired
	private SDownloadAttrService sDownloadAttrServiceImpl;

	@Autowired
	private SDownloadAttrContentService sDownloadAttrContentServiceImpl;

	@Autowired
	private SCategoriesQuoteService sCategoriesQuoteServiceImpl;

	@Autowired
	private SCategoriesService sCategoriesServiceImpl;

	@Autowired
	private SRepertoryQuoteService sRepertoryQuoteServiceImpl;

	@Autowired
	private HRepertoryService hRepertoryServiceImpl;

	@Autowired
	private CDownloadMapper cDownloadMapper;

	@Autowired
	private CRepertoryMapper cRepertoryMapper;

	@Autowired
	private CCategoriesMapper cCategoriesMapper;

	@Autowired
	private CDownloadAttrContentMapper cDownloadAttrContentMapper;

	@Override
	public String getSDownloadOrderBySSystem(SSystem sSystem) {
		if (sSystem == null) {
			return null;
		}
		DownloadSysConfig downloadSysConfig = SystemConfigUtil.downloadSysConfig(sSystem);
		int orderby = downloadSysConfig.getList().findOrderby();
		if (orderby == 1) {
			return "`s_download`.`is_top` DESC, `s_download`.`order_num` DESC, `s_download`.`id` DESC";
		} else if (orderby == 2) {
			return "`s_download`.`is_top` DESC, `s_download`.`order_num` ASC, `s_download`.`id` ASC";
		} else if (orderby == 3) {
			return "`s_download`.`is_top` DESC, `s_download`.`released_at` DESC, `s_download`.`id` DESC";
		} else if (orderby == 4) {
			return "`s_download`.`is_top` DESC, `s_download`.`released_at` ASC, `s_download`.`id` ASC";
		} else {
			return "`s_download`.`is_top` DESC, `s_download`.`order_num` DESC, `s_download`.`id` DESC";
		}
	}

	@Override
	@Transactional
	public Download insert(Download download) {
		SDownload downloadRequestData = download.getSDownload();
		// 获取当前 isTop 下最大排序号
		SDownload findByHostSiteSystemIdWithIsTopDesc = sDownloadServiceImpl.findByHostSiteSystemIdWithIsTopDesc(downloadRequestData.getHostId(),
				downloadRequestData.getSiteId(), downloadRequestData.getSystemId(), downloadRequestData.getIsTop());
		if (findByHostSiteSystemIdWithIsTopDesc == null) {
			downloadRequestData.setOrderNum(1);
		} else {
			int orderNum = findByHostSiteSystemIdWithIsTopDesc.getOrderNum() != null ? (findByHostSiteSystemIdWithIsTopDesc.getOrderNum().intValue() + 1) : 1;
			downloadRequestData.setOrderNum(orderNum);
		}

		SDownload sDownload = sDownloadServiceImpl.insert(downloadRequestData);
		if (sDownload == null || sDownload.getId() == null || sDownload.getId().longValue() < 1) {
			throw new RuntimeException("SDownload 写入数据失败 insert: " + download.getSDownload());
		}
		// 回写到 download 对象中
		download.setSDownload(sDownload);

		CategoryQuote categoryQuote = download.getCategoryQuote();
		if (categoryQuote != null) {
			SCategoriesQuote sCategoriesQuote = categoryQuote.getSCategoriesQuote();
			if (sCategoriesQuote != null) {
				sCategoriesQuote.setAimId(sDownload.getId());
				SCategoriesQuote insert = sCategoriesQuoteServiceImpl.insert(sCategoriesQuote);
				if (insert == null) {
					throw new RuntimeException("SCategoriesQuote 写入数据失败 insert: " + sCategoriesQuote);
				}
				categoryQuote.setSCategoriesQuote(insert);
				SCategories findByIdHostSiteId = sCategoriesServiceImpl.findByIdHostSiteId(insert.getCategoryId(), download.getSDownload().getHostId(),
						download.getSDownload().getSiteId());
				if (findByIdHostSiteId == null) {
					throw new RuntimeException("sCategoriesServiceImpl.findByIdHostSiteId 获取 SCategories 数据失败。 insert.getCategoryId()： "
							+ insert.getCategoryId() + " download.getSDownload().getHostId(): " + download.getSDownload().getHostId()
							+ " download.getSDownload().getSiteId(): " + download.getSDownload().getSiteId());
				}
				categoryQuote.setSCategories(findByIdHostSiteId);
				// 回写到 download 对象中
				download.setCategoryQuote(categoryQuote);
			}
		}

		List<DownloadAttrAndContent> listDownloadAttrAndContent = download.getListDownloadAttrAndContent();
		List<DownloadAttrAndContent> newListDownloadAttrAndContent = new ArrayList<>();
		SDownloadAttr sDownloadAttr = null;
		SDownloadAttrContent sDownloadAttrContent = null;
		for (DownloadAttrAndContent downloadAttrAndContent : listDownloadAttrAndContent) {
			sDownloadAttr = downloadAttrAndContent.getSDownloadAttr();
			if (sDownloadAttr.getType() != null && (sDownloadAttr.getType().shortValue() == (short) 3 || sDownloadAttr.getType().shortValue() == (short) 0)) {
				sDownloadAttrContent = downloadAttrAndContent.getSDownloadAttrContent();
				if (sDownloadAttrContent == null) {
					throw new RuntimeException("数据异常 sDownloadAttrContent 不能为空");
				}
				sDownloadAttrContent.setDownloadId(sDownload.getId());
				SDownloadAttrContent insert = sDownloadAttrContentServiceImpl.insert(sDownloadAttrContent);
				if (insert == null) {
					throw new RuntimeException("写入 SDownloadAttrContent 数据失败！sDownloadAttrContent: " + sDownloadAttrContent);
				}
				downloadAttrAndContent.setSDownloadAttrContent(insert);
			}
			SDownloadAttr findByHostSiteIdAndId = sDownloadAttrServiceImpl.findByHostSiteIdAndId(download.getSDownload().getHostId(),
					download.getSDownload().getSiteId(), sDownloadAttr.getId());
			if (findByHostSiteIdAndId == null) {
				throw new RuntimeException("sDownloadAttrServiceImpl.findByHostSiteIdAndId 获取 SDownloadAttr 数据失败。 download.getSDownload().getHostId(): "
						+ download.getSDownload().getHostId() + " download.getSDownload().getSiteId(): " + download.getSDownload().getSiteId()
						+ " sDownloadAttr.getId()： " + sDownloadAttr.getId());
			}
			downloadAttrAndContent.setSDownloadAttr(findByHostSiteIdAndId);
			newListDownloadAttrAndContent.add(downloadAttrAndContent);
		}
		// 回写到 download 对象中
		download.setListDownloadAttrAndContent(newListDownloadAttrAndContent);

		RepertoryQuote fileRepertoryQuote = download.getFileRepertoryQuote();
		if (fileRepertoryQuote != null && fileRepertoryQuote.getSRepertoryQuote() != null) {
			SRepertoryQuote sRepertoryQuote = fileRepertoryQuote.getSRepertoryQuote();
			sRepertoryQuote.setAimId(sDownload.getId());
			sRepertoryQuote.setParentId(0L);
			SRepertoryQuote insert = sRepertoryQuoteServiceImpl.insert(sRepertoryQuote);
			if (insert == null) {
				throw new RuntimeException("写入 SRepertoryQuote 数据失败！sRepertoryQuote: " + sRepertoryQuote);
			}
			fileRepertoryQuote.setSRepertoryQuote(insert);
			HRepertory findOne = hRepertoryServiceImpl.findOne(insert.getRepertoryId());
			if (findOne == null) {
				throw new RuntimeException("hRepertoryServiceImpl.findOne 获取 HRepertory 数据失败！insert.getRepertoryId(): " + insert.getRepertoryId());
			}
			fileRepertoryQuote.setHRepertory(findOne);
			// 回写到 download 对象中
			download.setFileRepertoryQuote(fileRepertoryQuote);
		}

		RepertoryQuote fileIconRepertoryQuote = download.getFileIconRepertoryQuote();
		if (fileIconRepertoryQuote != null && fileIconRepertoryQuote.getSRepertoryQuote() != null) {
			SRepertoryQuote sRepertoryQuote = fileIconRepertoryQuote.getSRepertoryQuote();
			sRepertoryQuote.setAimId(sDownload.getId());
			sRepertoryQuote.setParentId(0L);
			SRepertoryQuote insert = sRepertoryQuoteServiceImpl.insert(sRepertoryQuote);
			if (insert == null) {
				throw new RuntimeException("写入 SRepertoryQuote 数据失败！sRepertoryQuote: " + sRepertoryQuote);
			}
			fileIconRepertoryQuote.setSRepertoryQuote(sRepertoryQuote);
			HRepertory findOne = hRepertoryServiceImpl.findOne(insert.getRepertoryId());
			if (findOne == null) {
				throw new RuntimeException("hRepertoryServiceImpl.findOne 获取 HRepertory 数据失败！insert.getRepertoryId(): " + insert.getRepertoryId());
			}
			fileIconRepertoryQuote.setHRepertory(findOne);
			// 回写到 download 对象中
			download.setFileIconRepertoryQuote(fileIconRepertoryQuote);
		}

		return download;
	}

	@Override
	@Transactional
	public Download update(Download download) {
		SDownload sDownload = download.getSDownload();
		SDownload findByHostSiteIdAndId = sDownloadServiceImpl.findByHostSiteIdAndId(sDownload.getHostId(), sDownload.getSiteId(), sDownload.getId());
		if (findByHostSiteIdAndId == null) {
			throw new RuntimeException("获取需要更新的 SDownload 数据失败! sDownload.getId(): " + sDownload.getId() + " sDownload.getHostId(): " + sDownload.getHostId()
					+ " sDownload.getSiteId(): " + sDownload.getSiteId());
		}
		findByHostSiteIdAndId.setIsShow(sDownload.getIsShow()).setIsTop(sDownload.getIsTop());
		SDownload updateById = sDownloadServiceImpl.updateById(findByHostSiteIdAndId);
		if (updateById == null) {
			throw new RuntimeException("更新 SDownload 数据失败! findByHostSiteIdAndId: " + findByHostSiteIdAndId);
		}
		// 回 写 Download 数据
		download.setSDownload(updateById);

		// 更新分类数据
		CategoryQuote categoryQuote = download.getCategoryQuote();
		if (categoryQuote == null || categoryQuote.getSCategoriesQuote() == null) {
			// 删除之前拥有的分类数据
			boolean deleteBySystemAimId = sCategoriesQuoteServiceImpl.deleteBySystemAimId(updateById.getSystemId(), updateById.getId());
			if (!deleteBySystemAimId) {
				throw new RuntimeException("删除分类引用数据失败! updateById.getSystemId(): " + updateById.getSystemId() + " updateById.getId(): " + updateById.getId());
			}
			download.setCategoryQuote(null);
		} else {
			// 添加、修改分类数据
			List<SCategoriesQuote> findBySystemAimId = sCategoriesQuoteServiceImpl.findBySystemAimId(updateById.getSystemId(), updateById.getId());
			SCategoriesQuote updataSCategoriesQuote = null;
			if (CollectionUtils.isEmpty(findBySystemAimId)) {
				SCategoriesQuote sCategoriesQuote = categoryQuote.getSCategoriesQuote();
				sCategoriesQuote.setAimId(updateById.getId());
				updataSCategoriesQuote = sCategoriesQuoteServiceImpl.insert(sCategoriesQuote);
			} else if (findBySystemAimId.size() == 1) {
				SCategoriesQuote sCategoriesQuote = findBySystemAimId.get(0);
				sCategoriesQuote.setCategoryId(categoryQuote.getSCategoriesQuote().getCategoryId());
				updataSCategoriesQuote = sCategoriesQuoteServiceImpl.updateById(sCategoriesQuote);
			} else {
				boolean deleteBySystemAimId = sCategoriesQuoteServiceImpl.deleteBySystemAimId(updateById.getSystemId(), updateById.getId());
				if (!deleteBySystemAimId) {
					throw new RuntimeException(
							"删除分类引用数据失败! updateById.getSystemId(): " + updateById.getSystemId() + " updateById.getId(): " + updateById.getId());
				}
				SCategoriesQuote sCategoriesQuote = categoryQuote.getSCategoriesQuote();
				sCategoriesQuote.setAimId(updateById.getId());
				updataSCategoriesQuote = sCategoriesQuoteServiceImpl.insert(sCategoriesQuote);
			}
			if (updataSCategoriesQuote == null) {
				throw new RuntimeException("SCategoriesQuote 更新数据失败 findBySystemAimId: " + findBySystemAimId);
			}
			categoryQuote.setSCategoriesQuote(updataSCategoriesQuote);
			SCategories findByIdHostSiteId = sCategoriesServiceImpl.findByIdHostSiteId(updataSCategoriesQuote.getCategoryId(), updateById.getHostId(),
					updateById.getSiteId());
			if (findByIdHostSiteId == null) {
				throw new RuntimeException("sCategoriesServiceImpl.findByIdHostSiteId 获取 SCategories 数据失败。 updataSCategoriesQuote.getCategoryId()： "
						+ updataSCategoriesQuote.getCategoryId() + " updateById.getHostId(): " + updateById.getHostId() + " updateById.getSiteId(): "
						+ updateById.getSiteId());
			}
			categoryQuote.setSCategories(findByIdHostSiteId);
			// 回写到 download 对象中
			download.setCategoryQuote(categoryQuote);
		}

		// 更新属性
		List<DownloadAttrAndContent> listDownloadAttrAndContent = download.getListDownloadAttrAndContent();
		List<DownloadAttrAndContent> newListDownloadAttrAndContent = new ArrayList<>();
		SDownloadAttr sDownloadAttr = null;
		SDownloadAttrContent sDownloadAttrContent = null;
		SDownloadAttr findSDownloadAttr = null;
		for (DownloadAttrAndContent downloadAttrAndContent : listDownloadAttrAndContent) {
			sDownloadAttr = downloadAttrAndContent.getSDownloadAttr();
			sDownloadAttrContent = downloadAttrAndContent.getSDownloadAttrContent();
			findSDownloadAttr = sDownloadAttrServiceImpl.findByHostSiteIdAndId(updateById.getHostId(), updateById.getSiteId(), sDownloadAttr.getId());
			if (findSDownloadAttr == null) {
				throw new RuntimeException("sDownloadAttrServiceImpl.findByHostSiteIdAndId 获取 SDownloadAttr 数据失败。 updateById.getHostId(): "
						+ updateById.getHostId() + " updateById.getSiteId(): " + updateById.getSiteId() + " sDownloadAttr.getId()： " + sDownloadAttr.getId());
			}
			downloadAttrAndContent.setSDownloadAttr(findSDownloadAttr);

			if (findSDownloadAttr.getType() != null && (findSDownloadAttr.getType() == (short) 3 || findSDownloadAttr.getType() == (short) 0)) {
				if (sDownloadAttrContent == null) {
					throw new RuntimeException("数据异常 sDownloadAttrContent 不能为空");
				}
				SDownloadAttrContent updateSDownloadAttrContent = null;
				if (sDownloadAttrContent.getId() == null) {
					// 新增
					sDownloadAttrContent.setDownloadId(updateById.getId());
					updateSDownloadAttrContent = sDownloadAttrContentServiceImpl.insert(sDownloadAttrContent);
				} else {
					// 更新
					SDownloadAttrContent findByHostSiteIdAndId2 = sDownloadAttrContentServiceImpl.findByHostSiteIdAndId(updateById.getHostId(),
							updateById.getSiteId(), sDownloadAttrContent.getId());
					if (findByHostSiteIdAndId2 == null) {
						throw new RuntimeException("获取 SDownloadAttrContent 数据失败！updateById.getHostId(): " + updateById.getHostId()
								+ " updateById.getSiteId(): " + updateById.getSiteId() + " sDownloadAttrContent.getId(): " + sDownloadAttrContent.getId());
					}
					findByHostSiteIdAndId2.setContent(sDownloadAttrContent.getContent());
					updateSDownloadAttrContent = sDownloadAttrContentServiceImpl.updateById(findByHostSiteIdAndId2);
				}
				if (updateSDownloadAttrContent == null) {
					throw new RuntimeException("更新 SDownloadAttrContent 数据失败！sDownloadAttrContent: " + sDownloadAttrContent);
				}
				downloadAttrAndContent.setSDownloadAttrContent(updateSDownloadAttrContent);
			}
			newListDownloadAttrAndContent.add(downloadAttrAndContent);
		}
		// 回写到 download 对象中
		download.setListDownloadAttrAndContent(newListDownloadAttrAndContent);

		// 更新文件
		RepertoryQuote fileRepertoryQuote = download.getFileRepertoryQuote();
		SRepertoryQuote sRepertoryQuote = fileRepertoryQuote.getSRepertoryQuote();
		List<SRepertoryQuote> listSRepertoryQuote = sRepertoryQuoteServiceImpl.findByTypeAimId(sRepertoryQuote.getType(), updateById.getId());
		if (CollectionUtils.isEmpty(listSRepertoryQuote)) {
			sRepertoryQuote.setAimId(updateById.getId());
			sRepertoryQuote.setParentId(0L);
			SRepertoryQuote insert = sRepertoryQuoteServiceImpl.insert(sRepertoryQuote);
			if (insert == null) {
				throw new RuntimeException("写入 SRepertoryQuote 数据失败！sRepertoryQuote: " + sRepertoryQuote);
			}
			fileRepertoryQuote.setSRepertoryQuote(insert);
		} else if (listSRepertoryQuote.size() == 1) {
			SRepertoryQuote sRepertoryQuote2 = listSRepertoryQuote.get(0);
			sRepertoryQuote2.setRepertoryId(sRepertoryQuote.getRepertoryId());
			SRepertoryQuote updateById2 = sRepertoryQuoteServiceImpl.updateById(sRepertoryQuote2);
			if (updateById2 == null) {
				throw new RuntimeException("更新 SRepertoryQuote 数据失败！sRepertoryQuote: " + sRepertoryQuote);
			}
			fileRepertoryQuote.setSRepertoryQuote(updateById2);
		} else {
			sRepertoryQuoteServiceImpl.deleteByTypeAimId(sRepertoryQuote.getType(), updateById.getId());
			sRepertoryQuote.setAimId(updateById.getId());
			sRepertoryQuote.setParentId(0L);
			SRepertoryQuote insert = sRepertoryQuoteServiceImpl.insert(sRepertoryQuote);
			if (insert == null) {
				throw new RuntimeException("写入 SRepertoryQuote 数据失败！sRepertoryQuote: " + sRepertoryQuote);
			}
			fileRepertoryQuote.setSRepertoryQuote(insert);
		}
		HRepertory findOne = hRepertoryServiceImpl.findOne(sRepertoryQuote.getRepertoryId());
		if (findOne == null) {
			throw new RuntimeException("hRepertoryServiceImpl.findOne 获取 HRepertory 数据失败！insert.getRepertoryId(): " + sRepertoryQuote.getRepertoryId());
		}
		fileRepertoryQuote.setHRepertory(findOne);
		// 回写到 download 对象中
		download.setFileRepertoryQuote(fileRepertoryQuote);

		// 更新文件图标
		RepertoryQuote fileIconRepertoryQuote = download.getFileIconRepertoryQuote();
		if (fileIconRepertoryQuote != null && fileIconRepertoryQuote.getSRepertoryQuote() != null) {
			SRepertoryQuote sRepertoryQuoteIcon = fileIconRepertoryQuote.getSRepertoryQuote();
			List<SRepertoryQuote> listSRepertoryQuoteIcon = sRepertoryQuoteServiceImpl.findByTypeAimId(sRepertoryQuoteIcon.getType(), updateById.getId());
			if (CollectionUtils.isEmpty(listSRepertoryQuoteIcon)) {
				sRepertoryQuoteIcon.setAimId(updateById.getId());
				sRepertoryQuote.setParentId(0L);
				SRepertoryQuote insert = sRepertoryQuoteServiceImpl.insert(sRepertoryQuoteIcon);
				if (insert == null) {
					throw new RuntimeException("写入 SRepertoryQuote 数据失败！sRepertoryQuote: " + sRepertoryQuoteIcon);
				}
				fileIconRepertoryQuote.setSRepertoryQuote(insert);
			} else if (listSRepertoryQuoteIcon.size() == 1) {
				SRepertoryQuote sRepertoryQuote2 = listSRepertoryQuoteIcon.get(0);
				sRepertoryQuote2.setRepertoryId(sRepertoryQuoteIcon.getRepertoryId());
				SRepertoryQuote updateById2 = sRepertoryQuoteServiceImpl.updateById(sRepertoryQuote2);
				if (updateById2 == null) {
					throw new RuntimeException("更新 SRepertoryQuote 数据失败！sRepertoryQuote: " + sRepertoryQuoteIcon);
				}
				fileIconRepertoryQuote.setSRepertoryQuote(updateById2);
			} else {
				sRepertoryQuoteServiceImpl.deleteByTypeAimId(sRepertoryQuoteIcon.getType(), updateById.getId());
				sRepertoryQuoteIcon.setAimId(updateById.getId());
				sRepertoryQuote.setParentId(0L);
				SRepertoryQuote insert = sRepertoryQuoteServiceImpl.insert(sRepertoryQuoteIcon);
				if (insert == null) {
					throw new RuntimeException("写入 SRepertoryQuote 数据失败！sRepertoryQuote: " + sRepertoryQuoteIcon);
				}
				fileIconRepertoryQuote.setSRepertoryQuote(insert);
			}
			HRepertory hRepertory = hRepertoryServiceImpl.findOne(sRepertoryQuoteIcon.getRepertoryId());
			if (hRepertory == null) {
				throw new RuntimeException("hRepertoryServiceImpl.findOne 获取 HRepertory 数据失败！insert.getRepertoryId(): " + sRepertoryQuoteIcon.getRepertoryId());
			}
			fileIconRepertoryQuote.setHRepertory(hRepertory);
			// 回写到 download 对象中
			download.setFileIconRepertoryQuote(fileIconRepertoryQuote);
		}

		return download;
	}

	@Override
	public Download findByHostSiteDownloadId(long hostId, long siteId, long downloadId) {
		// 基础数据获取
		SDownload sDownload = sDownloadServiceImpl.findByHostSiteIdAndId(hostId, siteId, downloadId);
		if (sDownload == null) {
			return null;
		}

		// 分类获取
		CategoryQuote categoryQuote = null;
		List<SCategoriesQuote> listSCategoriesQuote = sCategoriesQuoteServiceImpl.findBySystemAimId(sDownload.getSystemId(), sDownload.getId());
		if (!CollectionUtils.isEmpty(listSCategoriesQuote)) {
			categoryQuote = new CategoryQuote();
			SCategoriesQuote sCategoriesQuote = listSCategoriesQuote.get(listSCategoriesQuote.size() - 1);
			if (sCategoriesQuote.getCategoryId() != null || sCategoriesQuote.getCategoryId().longValue() > 0L) {
				SCategories sCategories = sCategoriesServiceImpl.findByIdHostSiteId(sCategoriesQuote.getCategoryId(), sDownload.getHostId(),
						sDownload.getSiteId());
				if (sCategories != null) {
					categoryQuote.setSCategories(sCategories);
					categoryQuote.setSCategoriesQuote(sCategoriesQuote);
				}
			}
		}

		// 属性数据
		List<DownloadAttrAndContent> listDownloadAttrAndContent = cDownloadMapper.findDownloadAttrAndContentByHostSiteSystemAimId(sDownload.getHostId(),
				sDownload.getSiteId(), sDownload.getSystemId(), sDownload.getId());

		// 文件数据
		List<RepertoryQuote> listRepertoryQuote = cRepertoryMapper.findRepertoryQuoteByHostSiteTypeAimId(sDownload.getHostId(), sDownload.getSiteId(),
				(short) 7, sDownload.getId());
		RepertoryQuote fileRepertoryQuote = null;
		if (!CollectionUtils.isEmpty(listRepertoryQuote)) {
			fileRepertoryQuote = listRepertoryQuote.get(listRepertoryQuote.size() - 1);
		}

		// 图标
		listRepertoryQuote = cRepertoryMapper.findRepertoryQuoteByHostSiteTypeAimId(sDownload.getHostId(), sDownload.getSiteId(), (short) 8, sDownload.getId());
		RepertoryQuote fileIconRepertoryQuote = null;
		if (!CollectionUtils.isEmpty(listRepertoryQuote)) {
			fileIconRepertoryQuote = listRepertoryQuote.get(listRepertoryQuote.size() - 1);
		}

		Download download = new Download();
		download.setSDownload(sDownload).setCategoryQuote(categoryQuote).setListDownloadAttrAndContent(listDownloadAttrAndContent)
				.setFileRepertoryQuote(fileRepertoryQuote).setFileIconRepertoryQuote(fileIconRepertoryQuote);

		return download;
	}

	@Override
	public PageInfo<Download> findInfosByHostSiteSystemCategoryIdKeywordPageNumSize(long hostId, long siteId, long systemId, long categoryId, String keyword,
			int pageNum, int pageSize) {
		SSystem sSystem = sSystemServiceImpl.findSSystemByIdHostSiteId(systemId, hostId, siteId);
		if (sSystem == null) {
			return null;
		}

		// 找到需要搜的属性 id 列表
		List<SDownloadAttr> listSDownloadAttr = sDownloadAttrServiceImpl.findByHostSiteSystemId(hostId, siteId, systemId);
		List<Long> listAttrId = new ArrayList<>();
		Short attrCategorySearch = null;
		for (SDownloadAttr item : listSDownloadAttr) {
			Short isSearch = item.getIsSearch();
			Short isShow = item.getIsShow();
			Short type = item.getType();
			if ((type == 0 || type == 3) && isSearch == (short) 1 && isShow == (short) 1) {
				listAttrId.add(item.getId());
			}
			if (type == 2) {
				attrCategorySearch = isSearch;
			}
		}

		List<Long> categoryIdList = null;
		if (categoryId != -1L) {
			categoryIdList = new ArrayList<>();
			if (categoryId > 0) {
				List<SCategories> categoriesList = sCategoriesServiceImpl.findByAncestors(categoryId);
				for (SCategories categories : categoriesList)
					categoryIdList.add(categories.getId());
			}
		}

		// 构建模糊查询的 语句段落
		pageNum = pageNum < 1 ? 1 : pageNum;
		PageHelper.startPage(pageNum, pageSize);
		List<Download> listDownload = cDownloadMapper.findSDownloadByHostSiteSystemCategoryIdKeywordPageNumSize(hostId, siteId, systemId, categoryIdList,
				listAttrId, attrCategorySearch, keyword, getSDownloadOrderBySSystem(sSystem));
		if (CollectionUtils.isEmpty(listDownload)) {
			return null;
		}
		makeFullDownload(hostId, siteId, systemId, listDownload);
		PageInfo<Download> result = new PageInfo<>(listDownload);
		return result;
	}

	protected void makeFullDownload(long hostId, long siteId, long systemId, List<Download> list) {
		if (CollUtil.isEmpty(list)) {
			return;
		}
		List<Long> listId = new ArrayList<>();
		list.forEach(item -> {
			listId.add(item.getSDownload().getId());
		});

		// ids的分类数据
		List<CategoryQuote> listCategoryQuote = sCategoriesQuoteServiceImpl.findCategoryQuoteByHostSiteSystemAimId(hostId, siteId, systemId, listId);

		// ids的文件数据
		List<RepertoryQuote> listRepertoryQuote = cRepertoryMapper.findRepertoryQuoteByHostSiteTypeInAimId(hostId, siteId, (short) 7, listId);

		// ids的图标数据
		List<RepertoryQuote> listFileIconRepertoryQuote = cRepertoryMapper.findRepertoryQuoteByHostSiteTypeInAimId(hostId, siteId, (short) 8, listId);

		Iterator<Download> iterator = list.iterator();
		while (iterator.hasNext()) {
			Download download = iterator.next();
			SDownload sDownload = download.getSDownload();

			// 找到对应的分类数据
			CategoryQuote categoryQuote = getCategoryQuoteByList(sDownload, listCategoryQuote);

			// 属性数据
			List<DownloadAttrAndContent> listDownloadAttrAndContent = cDownloadMapper.findDownloadAttrAndContentByHostSiteSystemAimId(sDownload.getHostId(),
					sDownload.getSiteId(), sDownload.getSystemId(), sDownload.getId());

			// 文件数据
			RepertoryQuote fileRepertoryQuote = getRepertoryQuoteByList(sDownload, listRepertoryQuote);

			// 图标
			RepertoryQuote fileIconRepertoryQuote = getRepertoryQuoteByList(sDownload, listFileIconRepertoryQuote);

			download.setCategoryQuote(categoryQuote).setListDownloadAttrAndContent(listDownloadAttrAndContent).setFileRepertoryQuote(fileRepertoryQuote)
					.setFileIconRepertoryQuote(fileIconRepertoryQuote);
		}
	}

	@Override
	@Transactional
	public boolean deleteByListSDownload(List<SDownload> listSDownload) {
		if (CollectionUtils.isEmpty(listSDownload)) {
			return true;
		}
		for (SDownload sDownload : listSDownload) {
			if (sDownload.getId() != null && sDownload.getId().longValue() > 0) {
				sDownload.setIsRefuse((short) 1);
				SDownload updateById = sDownloadServiceImpl.updateById(sDownload);
				if (updateById == null || updateById.getId().longValue() != sDownload.getId().longValue()) {
					throw new RuntimeException("将数据移至回收站失败，被修改的数据! sDownload: " + sDownload);
				}
			}
		}
		return true;
	}

	@Override
	@Transactional
	public boolean clearBySystem(SSystem sSystem) {
		// 1. 首先删除资源的引用数据 s_repertory_quote，使用一条SQL语句实现
		List<Short> type = new ArrayList<>();
		type.add((short) 7); // 下载的文件
		type.add((short) 8); // 下载文件的 icon 图标
		cRepertoryMapper.deleteSDownloadRepertoryQuoteByHostSiteSystemId(sSystem.getHostId(), sSystem.getSiteId(), type, sSystem.getId());

		// 2. 删除 s_download_attr_content 数据
		boolean deleteByHostSiteSystemId = sDownloadAttrContentServiceImpl.deleteByHostSiteSystemId(sSystem.getHostId(), sSystem.getSiteId(), sSystem.getId());
		if (!deleteByHostSiteSystemId) {
			throw new RuntimeException("删除下载系统 s_download_attr_content 数据失败！ sSystem: " + sSystem);
		}

		// 3. 删除 s_download_attr 数据
		boolean deleteByHostSiteSystemId2 = sDownloadAttrServiceImpl.deleteByHostSiteSystemId(sSystem.getHostId(), sSystem.getSiteId(), sSystem.getId());
		if (!deleteByHostSiteSystemId2) {
			throw new RuntimeException("删除下载系统 s_download_attr 数据失败！ sSystem: " + sSystem);
		}

		// 4. 最后删除 s_download 数据
		boolean deleteByHostSiteSystemId3 = sDownloadServiceImpl.deleteByHostSiteSystemId(sSystem.getHostId(), sSystem.getSiteId(), sSystem.getId());
		if (!deleteByHostSiteSystemId3) {
			throw new RuntimeException("删除下载系统 s_download 数据失败！ sSystem: " + sSystem);
		}

		return true;
	}

	protected RepertoryQuote getRepertoryQuoteByList(SDownload sDownload, List<RepertoryQuote> listRepertoryQuote) {
		if (CollectionUtils.isEmpty(listRepertoryQuote)) {
			return null;
		}
		for (RepertoryQuote repertoryQuote : listRepertoryQuote) {
			if (repertoryQuote == null || repertoryQuote.getSRepertoryQuote() == null || repertoryQuote.getSRepertoryQuote().getAimId() == null) {
				continue;
			}
			long id = sDownload.getId().longValue();
			long downloadId = repertoryQuote.getSRepertoryQuote().getAimId().longValue();
			if (id == downloadId) {
				return repertoryQuote;
			}
		}
		return null;
	}

	protected CategoryQuote getCategoryQuoteByList(SDownload sDownload, List<CategoryQuote> listCategoryQuote) {
		if (CollectionUtils.isEmpty(listCategoryQuote)) {
			return null;
		}
		for (CategoryQuote categoryQuote : listCategoryQuote) {
			if (categoryQuote == null || categoryQuote.getSCategoriesQuote() == null || categoryQuote.getSCategoriesQuote().getAimId() == null) {
				continue;
			}
			long id = sDownload.getId().longValue();
			long downloadId = categoryQuote.getSCategoriesQuote().getAimId().longValue();
			if (id == downloadId) {
				return categoryQuote;
			}
		}
		return null;
	}

	@Override
	public boolean reductionByListSDownload(List<SDownload> listSDownload) {
		if (CollectionUtils.isEmpty(listSDownload)) {
			return true;
		}
		for (SDownload sDownload : listSDownload) {
			if (sDownload.getId() != null && sDownload.getId().longValue() > 0) {
				sDownload.setIsRefuse((short) 0);
				SDownload updateById = sDownloadServiceImpl.updateById(sDownload);
				if (updateById == null || updateById.getId().longValue() != sDownload.getId().longValue()) {
					throw new RuntimeException("将数据移至回收站失败，被修改的数据! sDownload: " + sDownload);
				}
			}
		}
		return true;
	}

	@Override
	public boolean cleanRecycle(List<SDownload> listSDownload) {
		if (CollUtil.isEmpty(listSDownload)) {
			return true;
		}
		SSystem sSystem = null;
		List<Long> ids = new ArrayList<>();
		for (SDownload sDownload : listSDownload) {
			if (sSystem == null) {
				sSystem = sSystemServiceImpl.findSSystemByIdHostSiteId(sDownload.getSystemId(), sDownload.getHostId(), sDownload.getSiteId());
			}
			Long id = sDownload.getId();
			if (id != null && id.longValue() > 0) {
				ids.add(sDownload.getId());
			}
		}

		if (sSystem == null || ids.size() < 1) {
			return false;
		}

		// 1. 删除 s_repertory_quote 数据
		List<Short> type = new ArrayList<>();
		type.add((short) 7); // 下载的文件
		type.add((short) 8); // 下载文件的 icon 图标
		cRepertoryMapper.deleteRecycleSDownloadRepertoryQuote(sSystem.getHostId(), sSystem.getSiteId(), type, sSystem.getId(), ids);

		// 2. 删除 s_categories_quote 数据
		cCategoriesMapper.deleteRecycleSDownloadSCategoryQuote(sSystem.getHostId(), sSystem.getSiteId(), sSystem.getId(), ids);

		// 3. 删除 s_download_attr_content 数据
		cDownloadAttrContentMapper.deleteRecycleSDownloadAttrContent(sSystem.getHostId(), sSystem.getSiteId(), sSystem.getId(), ids);

		// 4. 删除 s_download 数据
		cDownloadMapper.deleteRecycleSDownload(sSystem.getHostId(), sSystem.getSiteId(), sSystem.getId(), ids);

		return true;
	}

	@Override
	public boolean cleanRecycleAll(SSystem sSystem) {
		if (sSystem == null) {
			return false;
		}

		// 1. 删除 s_repertory_quote 数据
		List<Short> type = new ArrayList<>();
		type.add((short) 7); // 下载的文件
		type.add((short) 8); // 下载文件的 icon 图标
		cRepertoryMapper.deleteRecycleSDownloadRepertoryQuote(sSystem.getHostId(), sSystem.getSiteId(), type, sSystem.getId(), null);

		// 2. 删除 s_categories_quote 数据
		cCategoriesMapper.deleteRecycleSDownloadSCategoryQuote(sSystem.getHostId(), sSystem.getSiteId(), sSystem.getId(), null);

		// 3. 删除 s_download_attr_content 数据
		cDownloadAttrContentMapper.deleteRecycleSDownloadAttrContent(sSystem.getHostId(), sSystem.getSiteId(), sSystem.getId(), null);

		// 4. 删除 s_download 数据
		cDownloadMapper.deleteRecycleSDownload(sSystem.getHostId(), sSystem.getSiteId(), sSystem.getId(), null);

		return true;
	}

	@Override
	public int searchOkTotal(long hostId, long siteId, long systemId, String keyword) {
		int searchTotal = cDownloadMapper.searchOkTotal(hostId, siteId, systemId, keyword);
		return searchTotal;
	}

	@Override
	public PageInfo<Download> searchOkInfos(long hostId, long siteId, long systemId, String keyword, int page, int size) {
		SSystem sSystem = sSystemServiceImpl.findSSystemByIdHostSiteId(systemId, hostId, siteId);
		if (sSystem == null) {
			return null;
		}
		PageHelper.startPage(page, size);
		List<Download> listDownload = cDownloadMapper.searchOkInfos(hostId, siteId, systemId, keyword, getSDownloadOrderBySSystem(sSystem));
		if (CollUtil.isEmpty(listDownload)) {
			return null;
		}
		makeFullDownload(hostId, siteId, systemId, listDownload);
		PageInfo<Download> result = new PageInfo<>(listDownload);
		return result;
	}

	@Override
	@Transactional
	public int repertoryImport(FeignRepertoryImport repertoryImport) {
		SSystem sSystem = repertoryImport.getSSystem();
		List<HRepertory> listHRepertory = repertoryImport.getListHRepertory();
		if (sSystem == null) {
			return 0;
		}
		if (CollUtil.isEmpty(listHRepertory)) {
			return 0;
		}

		Long hostId = sSystem.getHostId();
		Long siteId = sSystem.getSiteId();
		Long systemId = sSystem.getId();

		List<SDownloadAttr> listSDownloadAttr = sDownloadAttrServiceImpl.findByHostSiteSystemId(hostId, siteId, systemId);
		Optional<SDownloadAttr> findFirst = listSDownloadAttr.stream().filter(item -> {
			return item.getType() != null && item.getType().shortValue() == (short) 3;
		}).findFirst();
		if (!findFirst.isPresent()) {
			return 0;
		}
		SDownloadAttr sDownloadAttr = findFirst.get();
		int count = 0;
		for (HRepertory hRepertory : listHRepertory) {
			String originalFilename = hRepertory.getOriginalFilename();
			Short type = hRepertory.getType();
			if (type == null || type.shortValue() != (short) 1) {
				continue;
			}

			SDownload sDownload = new SDownload();
			sDownload.setHostId(hostId).setSiteId(siteId).setSystemId(systemId).setIsShow((short) 1).setIsRefuse((short) 0).setIsTop((short) 0).setOrderNum(1)
					.setReleasedAt(DateUtil.date().toJdkDate());
			SDownload insertSDownload = sDownloadServiceImpl.insert(sDownload);
			if (insertSDownload == null || insertSDownload.getId() == null || insertSDownload.getId().longValue() < 1) {
				throw new RuntimeException("SDownload 写入数据失败 sDownload: " + sDownload);
			}

			SDownloadAttrContent sDownloadAttrContent = new SDownloadAttrContent();
			sDownloadAttrContent.setHostId(hostId).setSiteId(siteId).setSystemId(systemId).setDownloadId(insertSDownload.getId())
					.setDownloadAttrId(sDownloadAttr.getId()).setContent(originalFilename);
			SDownloadAttrContent insertSDownloadAttrContent = sDownloadAttrContentServiceImpl.insert(sDownloadAttrContent);
			if (insertSDownloadAttrContent == null) {
				throw new RuntimeException("写入 SDownloadAttrContent 数据失败！sDownloadAttrContent: " + sDownloadAttrContent);
			}

			SRepertoryQuote sRepertoryQuote = new SRepertoryQuote();
			sRepertoryQuote.setHostId(hostId).setSiteId(siteId).setParentId(0L).setRepertoryId(hRepertory.getId()).setType((short) 7).setAimId(sDownload.getId()).setOrderNum(1).setConfig("");
			SRepertoryQuote insertSRepertoryQuote = sRepertoryQuoteServiceImpl.insert(sRepertoryQuote);
			if (insertSRepertoryQuote == null) {
				throw new RuntimeException("写入 SRepertoryQuote 数据失败！sRepertoryQuote: " + sRepertoryQuote);
			}
			count++;
		}
		return count;
	}
}
